<template>
  <div class="app-container">
    <div class="search-container">
      <el-form :model="searchParam" :inline="true" label-width="65px">
        <el-form-item label="工厂">
          <el-select
            @keyup.enter="search"
            v-model="searchParam.plantId"
            placeholder="请选择工厂"
            clearable
            @change="changePlant"
          >
            <el-option
              v-for="item in plantList"
              :key="item.id"
              :label="item.organizationCode"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="工作中心">
          <el-select
            @keyup.enter="search"
            v-model="searchParam.workCenterIds"
            placeholder="请选择工作中心"
            clearable
            filterable
            multiple
            collapse-tags
            collapse-tags-tooltip
            style="width: 300px"
          >
            <el-option
              v-for="item in workshopList"
              :key="item.id"
              :label="`${item.workshopCode}-${item.workshopName}`"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="工作年份">
          <el-select
            @keyup.enter="search"
            v-model="searchParam.planYear"
            placeholder="请选择工作年份"
            clearable
            @change="selectYear"
          >
            <el-option
              v-for="item in yearOptions"
              :key="item"
              :value="item"
              :label="item"
            />
          </el-select>
        </el-form-item>
        <!-- <el-form-item label="工作月">
          <el-select
            @keyup.enter="search"
            v-model="searchParam.month"
            placeholder="请选择工作月"
            clearable
            @change="selectMonth"
          >
            <el-option
              v-for="item in monthList"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item> -->
        <el-form-item label="状态">
          <el-select
            v-model="searchParam.orderState"
            placeholder="请选择状态"
            clearable
          >
            <el-option
              v-for="item in useDictionary('PlanStateList')"
              :key="item.value"
              :label="item.label"
              :value="Number(item.value)"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="开始周数">
          <el-select
            @keyup.enter="search"
            v-model="searchParam.planWeekStart"
            placeholder="请选择开始周数"
            clearable
          >
            <el-option
              v-for="item in monthOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="结束周数">
          <el-select
            @keyup.enter="search"
            v-model="searchParam.planWeekEnd"
            placeholder="请选择结束周数"
            clearable
          >
            <el-option
              v-for="item in monthOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <!-- <el-form-item label="开始周数">
          <el-date-picker
            v-model="searchParam.planWeekStart"
            type="week"
            format="[Week] ww"
            value-format="ww"
            placeholder="请输入开始周"
          />
        </el-form-item>
        <el-form-item label="结束周数">
          <el-date-picker
            v-model="searchParam.planWeekEnd"
            type="week"
            format="[Week] ww"
            placeholder="请输入开始周"
            value-format="ww"
          />
        </el-form-item> -->
        <el-form-item>
          <el-button type="primary" @click="search"
            ><i-ep-search />搜索</el-button
          >
          <el-button @click="reset"><i-ep-refresh />重置</el-button>
        </el-form-item>
      </el-form>
      <!-- 导入周计划 -->
      <ImportExcel ref="weekImportRef" />
    </div>

    <el-card shadow="never" class="table-container">
      <template #header>
        <!-- <el-button @click="weekBatchImport"
          ><template #icon><i-ep-upload /></template>导入计划</el-button
        > -->
        <!-- <el-button @click="dailyBatchImport"
          ><template #icon><i-ep-upload /></template>导入日计划</el-button
        > -->
        <el-button
          :disabled="ids.length == 0"
          type="primary"
          @click="oderIssuance"
          >批量下达</el-button
        >
      </template>

      <el-table
        ref="dataTableRef"
        v-loading="loading"
        :data="tableData"
        highlight-current-row
        border
        @selection-change="handleSelectionChange"
      >
        <el-table-column
          type="selection"
          width="55"
          :selectable="selected"
          align="center"
        />
        <el-table-column type="index" width="55" label="序号" align="center" />
        <el-table-column
          label="总成//工序-人数-版本号"
          prop="plantCode"
          min-width="200"
          show-overflow-tooltip
        >
          <template #default="scope">
            {{ scope.row.descriptionCode
            }}{{ scope.row.descriptionCode && scope.row.versionNo ? "-" : ""
            }}{{ scope.row.versionNo }}
          </template>
        </el-table-column>
        <el-table-column
          label="工厂"
          prop="plantCode"
          min-width="100"
          show-overflow-tooltip
        />
        <el-table-column
          label="工作中心"
          prop="workCenterName"
          min-width="150"
          show-overflow-tooltip
        >
          <template #default="scope">
            {{ scope.row.workCenterCode }}-{{ scope.row.workCenterName }}
          </template>
        </el-table-column>
        <el-table-column
          label="班产"
          prop="yield"
          min-width="100"
          show-overflow-tooltip
          header-align="center"
          align="right"
        />
        <el-table-column
          label="状态"
          prop="orderState"
          min-width="100"
          align="center"
        >
          <template #default="scope">
            <el-tag v-if="scope.row.orderState == 0" type="success">{{
              useDictionary("PlanStateList", scope.row.orderState ?? "")
            }}</el-tag>
            <el-tag v-if="scope.row.orderState != 0">{{
              useDictionary("PlanStateList", scope.row.orderState ?? "")
            }}</el-tag>
          </template>
        </el-table-column>
        <!-- <el-table-column
          label="计划时间"
          prop="planDate"
          width="100"
          show-overflow-tooltip
        >
          <template #default="scope"> {{ scope.row.planDate }}周 </template>
        </el-table-column> -->
        <el-table-column
          label="工作年"
          prop="planYear"
          min-width="100"
          show-overflow-tooltip
        >
          <template #default="scope"> {{ scope.row.planYear }}年</template>
        </el-table-column>
        <el-table-column
          label="工作周"
          prop="planWeek"
          min-width="100"
          show-overflow-tooltip
        >
          <template #default="scope"> {{ scope.row.planWeek }}周 </template>
        </el-table-column>
        <!-- <el-table-column
          label="周计划数量"
          prop="planWeekQuantity"
          width="120"
          show-overflow-tooltip
          header-align="center"
          align="right"
        /> -->
        <el-table-column
          label="计划数量"
          prop="planQuantity"
          min-width="140"
          show-overflow-tooltip
          header-align="center"
          align="right"
        >
          <template #default="{ $index, row }">
            <!-- 分行校验的关键在于:prop="'grossProfits.' + $index + '.name'" -->

            <span>{{ row.planQuantity }}</span>
          </template>
        </el-table-column>

        <el-table-column
          label="生产批次"
          prop="planBatch"
          min-width="100"
          show-overflow-tooltip
        >
          <template #default="{ $index, row }">
            <!-- 分行校验的关键在于:prop="'grossProfits.' + $index + '.name'" -->

            <span>{{ row.planBatch }}</span>
          </template>
        </el-table-column>

        <el-table-column
          label="已完成数量"
          prop="planFinishQuantity"
          min-width="100"
          show-overflow-tooltip
          header-align="center"
          align="right"
        />
      </el-table>

      <el-pagination
        :background="true"
        :current-page="pageable.pageNum"
        :page-size="pageable.pageSize"
        :page-sizes="[10, 25, 50, 100]"
        :total="pageable.total"
        layout="total, sizes, prev, pager, next, jumper"
        class="mt-[20px]"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </el-card>

    <!-- <mesworkorderplan-edit
      :visible="addDialog.visible"
      :title="addDialog.title"
      :data="addDialog.data"
      @reset-table="(id:string) => (id?.length ? getTableList() : reset())"
      :is-readonly="addDialog.readvisible"
      @change-visible="changeVisible"
    /> -->
  </div>
</template>

<script setup lang="ts">
import { useTable, useDownload, useDictionary } from "@/utils/useTable";
import dayjs from "dayjs";
import request from "@/utils/request";
import {
  getFirstWorkShopList,
  getMesRouteGroupList,
  getWorkCenterDetail,
  getCurrentYield,
  getFreeDetails,
  getMonthList,
  getYearList,
  getMaterialList,
  getDateshiftCount,
} from "@/utils/commonData";
import {
  getWeeksInYear,
  getWeekNumber,
  week_date,
  getDaysOfCurrentWeek,
} from "@/utils/dateUtils";
import { disabledTimeListsProps } from "element-plus/es/components/time-picker/src/props/shared";
defineOptions({
  name: "MESMESORDERISSUANCE",
  inheritAttrs: false,
});

// 请求参数
const requestApi = "mes/mesworkorder/queryByPage";

// 是否需要分页
const pagination = true;

const initParam = {};
const currentYear = new Date().getFullYear(); // 当前年份
const currentMonth = dayjs().month() + 1; // 当前年份
const currentWeek = getWeekNumber(new Date()); // 当前第几周
// 初始化搜索参数数据
const searchParamInit = {
  month: currentMonth,
  planYear: currentYear,
  workCenterId: "",
  plantId: "",
  planBatch: "",
  planWeek: "",
  planWeekEnd: currentWeek,
  planWeekStart: currentWeek,
  orderState: "",
  workCenterIds: [],
  // groupType: "",
};
const deleteParam = {
  api: "/mes/mesworkorderplan/closePlan",
  data: {},
};

// 数据请求错误后处理
function requestError() {}

const dataCallBack = ref(undefined); // 无需二次数据处理&不传赞数也行

// 表格操作 Hooks
const {
  tableData,
  pageable,
  searchParam,
  ids,
  getTableList,
  search,
  reset,
  handleSizeChange,
  handleCurrentChange,
  handleSelectionChange,
  handleTableDelete,
  loading,
}: any = useTable(
  requestApi,
  initParam,
  searchParamInit,
  pagination,
  dataCallBack.value,
  requestError,
  deleteParam
);

onMounted(async () => {
  yearOptions.value = await getYearList();
  monthOptions.value = getMonthList(currentYear);
  getTableList();
  getPlantList();
});

const addDialog = reactive<DialogOption>({
  visible: false,
  readvisible: false,
  title: "",
  data: {},
});

// 获取周列表

const monthOptions = ref<OptionType[]>();

// 获取年度列表
const yearOptions = ref();

// 年度变更重新获取月份
function selectYear(e: number) {
  if (e) {
    searchParam.value = {
      ...searchParam.value,
      planWeekStart: "",
      planWeekEnd: "",
    };
    monthOptions.value = getMonthList(e);
  } else {
    monthOptions.value = [];
    searchParam.value = {
      ...searchParam.value,
      planWeekStart: "",
      planWeekEnd: "",
    };
  }
}

// 月份
const monthList = [
  {
    id: 1,
    name: "1月",
  },
  {
    id: 2,
    name: "2月",
  },
  {
    id: 3,
    name: "3月",
  },
  {
    id: 4,
    name: "4月",
  },
  {
    id: 5,
    name: "5月",
  },
  {
    id: 6,
    name: "6月",
  },
  {
    id: 7,
    name: "7月",
  },
  {
    id: 8,
    name: "8月",
  },
  {
    id: 9,
    name: "9月",
  },
  {
    id: 10,
    name: "10月",
  },
  {
    id: 11,
    name: "11月",
  },
  {
    id: 12,
    name: "12月",
  },
];

const selectMonth = (e) => {
  if (e) {
    searchParam.value.month = e;
  } else {
    searchParam.value.month = "";
  }
};
// 查询详情
async function getInfo(id: string) {
  request({
    url: `/mes/mesworkorderplan/get/${id}`,
    method: "get",
  })
    .then((data) => {
      addDialog.data = data.data;
      addDialog.visible = true;
    })
    .catch((res) => {
      console.log(res);
    });
}

/** 打开加工单计划明细表单弹窗 */
function openDialog(roleObj?: Object) {
  if (roleObj) {
    addDialog.title = "修改加工单计划明细";
    getInfo(roleObj.id);
  } else {
    addDialog.title = "新增加工单计划明细";
    addDialog.visible = true;
  }
  addDialog.readvisible = false;
}

/** 打开加工单计划明细表单弹窗 详情 */
function openDialogdetail(roleObj?: any) {
  addDialog.title = "加工单计划明细详情";
  getInfo(roleObj.id);
  addDialog.readvisible = true;
}

function changeVisible(value: boolean) {
  addDialog.visible = value;
  if (!value) {
    addDialog.data = {};
  }
}

function getplanDate(data: any) {
  if (data) {
    searchParam.value.planWeekStart = data[0];
    searchParam.value.planWeekEnd = data[1];
  } else {
    searchParam.value.planWeekStart = "";
    searchParam.value.planWeekEnd = "";
  }
}
//时间格式处理，yyyy-mm-dd
function formatDate(row, column) {
  const date = row[column.property];
  if (!date) return "";
  return date.split(" ")[0]; // 返回日期的年月日部分，而隐藏时间部分
}

//工厂列表
const plantList = ref([]);
const getPlantList = async () => {
  const { data } = await request({
    url: "system/sysOrganization/getList",
    method: "post",
    data: { organizationType: 3 },
  });
  plantList.value = data;
  searchParam.value.plantId = plantList.value[0].id;
  changePlant(searchParam.value.plantId);
};
function changePlant(plantId: String) {
  getWorkshopList(plantId);
  searchParam.value = { ...searchParam.value, workCenterId: "" };
}
//工作中心
const workshopList = ref([]);
const getWorkshopList = async (plantId: String) => {
  const { data } = await request({
    url: "mes/mesworkshop/getList",
    method: "post",
    data: { plantId: plantId },
  });
  workshopList.value = data;
};

// 导入周数据
const weekImportRef = ref();
async function weekImportApiFunc(formdata: FormData, config: any) {
  await request
    .post("/mes/mesworkorder/importPlanClose", formdata, config)
    .then((res) => {
      ElMessage.success(`成功导入${res.data}条数据！`);
    });
}
const weekBatchImport = () => {
  if (!searchParam.value.month || !searchParam.value.planYear) {
    ElMessage.error("请选择工作月、工作年份，再操作！");
  } else {
    let newSearchParam = { ...searchParam.value };

    let params = {
      title: "导入周计划",
      tempApi: "/mes/mesworkorder/exportTemp", //模板下载
      importApi: weekImportApiFunc, // 导入
      getTableList: startSearch1, // 成功后回调
      isShowTemp: false,
      fileTypes: ".xlsx",
      searchParam: newSearchParam,
    };
    weekImportRef.value.acceptParams(params);
  }
};
// 后加的代码--
async function startSearch1() {
  search();
}

// tableData.value = [];
// isSearched.value = false;
// if (!searchParam.value.plantId) {
//   ElMessage.error("请选择工厂");
//   return;
// } else if (!searchParam.value.workCenterId) {
//   ElMessage.error("请选择工作中心");
//   return;
// } else if (!searchParam.value.planYear) {
//   ElMessage.error("请选择年份");
//   return;
// } else if (!searchParam.value.planWeek) {
//   ElMessage.error("请选择工作周");
//   return;
// } else {
//   // 工作中心详情
//   const { workCenterId, planYear, plantId } = searchParam.value;
//   workCenterDetail.value = await getWorkCenterDetail(workCenterId);
//   dateshiftCount.value = await getDateshiftCount(searchParam.value);
//   if (dateshiftCount.value.length === 0) {
//     ElMessage.error("请先设置排班");
//     return;
//   }
//   // 获取最大负荷率
//   maxCapacityLoad.value = workCenterDetail.value.maxCapacityLoad;
//   // 获取休息日数据
//   freeDetail.value = await getFreeDetails(plantId, planYear);
//   // 获取物料下拉列表
//   routingAllocationIdList.value = await getMaterialList(
//     searchParam.value.plantId,
//     searchParam.value.workCenterId
//   );
//   search();
// }

const downLoadExcel = () => {
  useDownload(
    "/mes/mesworkorder//exportPlanClose",
    "加工单",
    searchParam.value,
    true,
    ".xlsx"
  );
};

// 批量下达
const idsList = ref([]);
const oderIssuance = async () => {
  ElMessageBox.confirm("确认批量下达已选数据项?", "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(async () => {
    idsList.value = [];
    tableData.value.forEach((item, index) => {
      ids.value.forEach((i) => {
        if (item.id == i) {
          idsList.value.push(i);
        }
      });
    });

    await request({
      url: "/mes/mesworkorder/issuePlanBatch",
      method: "post",
      data: { ids: idsList.value },
    }).then((res) => {
      ElMessage.success("批量下达成功！");
      search();
    });
  });
};
// 停用过滤
const selected = (row) => {
  if (row.orderState == 0) {
    return true; //可勾选
  } else {
    return false; //不可勾选
  }
};
</script>
<style lang="scss" scoped>
:deep(.el-form .el-form-item__label) {
  width: 63px;
}
</style>
